/**
 * Copyright (c) 2017-2020 四川智慧云天 All rights reserved.
 *
 * https://www.sczhyt.cn
 *
 * 版权所有，侵权必究！
 */

package cn.sczhyt.modules.sys.controller;

import cn.sczhyt.modules.sys.service.SysRoleDeptService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import cn.sczhyt.common.annotation.SysLog;
import cn.sczhyt.common.exception.RRException;
import cn.sczhyt.common.utils.Constant;
import cn.sczhyt.common.utils.PageUtils;
import cn.sczhyt.common.utils.R;
import cn.sczhyt.common.validator.ValidatorUtils;
import cn.sczhyt.modules.sys.dao.SysOrganizeInfoDao;
import cn.sczhyt.modules.sys.entity.SysOrganizeInfoEntity;
import cn.sczhyt.modules.sys.entity.SysRoleEntity;
import cn.sczhyt.modules.sys.entity.vo.RoleIdAndRoleNameEntity;
import cn.sczhyt.modules.sys.entity.vo.RoleSearchEntity;
import cn.sczhyt.modules.sys.entity.vo.UserInfoVoEntity;
import cn.sczhyt.modules.sys.service.SysRoleMenuService;
import cn.sczhyt.modules.sys.service.SysRoleService;
import cn.sczhyt.modules.sys.service.SysUserRoleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 角色管理
 *
 * @author Mark sunlightcs@gmail.com
 */
@Api(tags = "角色管理")
@RestController
@RequestMapping("/sys/role")
public class SysRoleController extends AbstractController {
	@Autowired
	private SysRoleService sysRoleService;
	@Autowired
	private SysRoleMenuService sysRoleMenuService;
	@Autowired
	private SysOrganizeInfoDao organizeInfoDao;
	@Autowired
	private SysRoleDeptService sysRoleDeptService;
	@Autowired
	SysUserRoleService userRoleService;


	/**
	 * 角色id与角色名
	 */
	@ApiOperation("角色id与角色名字")
	@GetMapping("/list/all")
	public R listRoleIds(){
		List<RoleIdAndRoleNameEntity> list = sysRoleService.listIdAndName();

		return R.ok().put("data", list);
	}


	/**
	 * 根据角色id,搜索对应的用户
	 */
	@ApiOperation("根据角色id,搜索对应的用户")
	@RequestMapping("/list/userIds")
	public R listUserIds(@RequestParam(defaultValue = "1") Integer page,
						 @RequestParam(defaultValue = "10") Integer limit,
						 @RequestBody(required = false) RoleSearchEntity search){
		if (search == null) {
			throw new RRException("你传的参数为空，你要重新看看自己的");
		}
		if (search.getRoleId().equals("1")) {

			IPage<UserInfoVoEntity> iPage = sysRoleService.listUserIdsByRoleId(page,limit,search);
			PageUtils list = new PageUtils(iPage);

			return R.ok().put("data", list);
		}
			IPage<UserInfoVoEntity> iPage = sysRoleService.listOrgByRoleId(page,limit,search);

			PageUtils list = new PageUtils(iPage);

			return R.ok().put("data", list);
	}
	/**
	 * 角色列表
	 */
	@ApiOperation("角色列表")
	@GetMapping("/list")
	//@RequiresPermissions("sys:role:list")
	public R list(@RequestParam Map<String, Object> params){
		//如果不是超级管理员，则只查询自己创建的角色列表
		if(!getUserId().equals(Constant.SUPER_ADMIN)){
			params.put("createUserId", getUserId());
		}

		PageUtils page = sysRoleService.queryPage(params);

		return R.ok().put("data", page);
	}
	
	/**
	 * 角色列表
	 */
	@ApiOperation("角色列表")
	@GetMapping("/select")
	@RequiresPermissions("sys:role:select")
	public R select(){
		Map<String, Object> map = new HashMap<>();
		
		//如果不是超级管理员，则只查询自己所拥有的角色列表
		if(!getUserId().equals(Constant.SUPER_ADMIN)){
			map.put("create_user_id", getUserId());
		}
		List<SysRoleEntity> list = (List<SysRoleEntity>) sysRoleService.listByMap(map);
		
		return R.ok().put("data", list);
	}
	
	/**
	 * 角色信息
	 */
	@ApiOperation("角色信息")
	@GetMapping("/info/{roleId}")
	@RequiresPermissions("sys:role:info")
	public R info(@PathVariable("roleId") String roleId){
		SysRoleEntity role = sysRoleService.getById(roleId);


		//查询角色对应的菜单
		List<String> menuIdList = sysRoleMenuService.queryMenuIdList(roleId);

		//查询角色对应的部门
		List<String> deptIdList = sysRoleDeptService.queryDeptIdList(new String[]{roleId});

		role.setDeptIdList(deptIdList);

		role.setMenuIdList(menuIdList);
		
		return R.ok().put("data", role);
	}

	/**
	 * 通过部门Id查询角色
	 */
	@ApiOperation("通过部门Id查询角色")
	@GetMapping("/info/dept/{deptId}")
	@RequiresPermissions("sys:role:info")
	public R findRoleByDeptId(@PathVariable("deptId") String deptId){

		//获取当前部门所有的角色
		List<SysRoleEntity> list = sysRoleService.getByDeptId(deptId);
		ArrayList<String> arrayList = new ArrayList<>();

		for (int i = 0; i < list.size(); i++) {
			List<String> roleIdList = userRoleService.queryRoleIdList(list.get(i).getRoleId());
			for (int j = 0; j < roleIdList.size(); j++) {
				String s = roleIdList.get(j);
				int a = 0;
					a =	a++;
				arrayList.add(a,s);
			}
		}
		String[] roleIds = arrayList.toArray(new String[arrayList.size()]);
		System.out.println(roleIds);
		//通过roleIds查询userIds
		List<String> userIds = userRoleService.queryUserIdList(roleIds);
		//通过userIds查询userInfo

		List<SysOrganizeInfoEntity> organizeInfoEntities = organizeInfoDao.selectByUserIds(userIds);

		return R.ok().put("data", organizeInfoEntities);
	}

	/**
	 * 保存角色
	 */
	@ApiOperation("保存角色")
	@SysLog("保存角色")
	@PostMapping("/save")
	@RequiresPermissions("sys:role:save")
	public R save(@RequestBody SysRoleEntity role){
		ValidatorUtils.validateEntity(role);


		System.out.println("角色保存"+role.toString());
		
		role.setCreateUserId(getUserId());
		sysRoleService.saveRole(role);
		
		return R.ok();
	}
	
	/**
	 * 修改角色
	 */
	@ApiOperation("修改角色")
	@SysLog("修改角色")
	@PostMapping("/update")
	@RequiresPermissions("sys:role:update")
	public R update(@RequestBody SysRoleEntity role){
		ValidatorUtils.validateEntity(role);

		System.out.println("修改"+role);
		
		role.setCreateUserId(getUserId());

		sysRoleService.update(role);
		
		return R.ok();
	}
	
	/**
	 * 删除角色
	 */
	@ApiOperation("删除角色")
	@SysLog("删除角色")
	@PostMapping("/delete")
	@RequiresPermissions("sys:role:delete")
	public R delete(@RequestBody String[] roleIds){
		sysRoleService.deleteBatch(roleIds);
		
		return R.ok();
	}
}
